#include "stdafx.h"
#include "Texture.h"
#include "Utils.h"

cTexture::cTexture(): m_ID(-1), m_type(-1), m_wrap(-1), m_filter(-1), m_textureID(0)
{
	for (int i=0; i<6; i++)
	{
		memset(m_fileTexture[i], '\0', MAX_LENGTH_NAME);
	}
}

cTexture::cTexture(int id, int type, GLint wrap, GLint filter, const char **fileTexture)
{
	cTexture();
	m_ID = id;
	m_type = type;
	m_wrap = wrap;
	m_filter = filter;

	if(type != TEXTURE_CUBE_MAP)
	{
		int j = 0;
		while(*fileTexture[j] != '\0')
		{
			m_fileTexture[0][j] = *fileTexture[j];
			j++;
		}
	}
	else
	{
		for (int i=0; i<6; i++)
		{
			int j = 0;
			while(fileTexture[i][j] != '\0')
			{
				m_fileTexture[i][j] = fileTexture[i][j];
				j++;
			}
		}
	}
}

cTexture::~cTexture()
{
	glDeleteTextures(1, &m_textureID);
}

void cTexture::Init()
{
	if (m_textureID > 0) //already init
	{
		return;
	}

	glGenTextures(1, &m_textureID);

	if(m_type != TEXTURE_CUBE_MAP)
	{
		char *ft_url = JoinString(TEXTURES_PATH, m_fileTexture[0]);
		int width, height, bpp;
		char *imageData;

		glBindTexture(GL_TEXTURE_2D, m_textureID);

		imageData = LoadTGA(ft_url, &width, &height,&bpp);
		glTexImage2D(GL_TEXTURE_2D, 0, (bpp == 24 ? GL_RGB : GL_RGBA), width, height, 0, (bpp == 24 ? GL_RGB : GL_RGBA), GL_UNSIGNED_BYTE, imageData);

		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, m_wrap);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, m_wrap);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, m_filter);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, m_filter);

		SAFE_DEL_ARRAY(ft_url);
		SAFE_DEL_ARRAY(imageData);
	}
	else
	{
		char *ft_url;
		int width, height, bpp;
		char *imageData;
		
		glBindTexture(GL_TEXTURE_CUBE_MAP, m_textureID);
		for (int i=0; i<6; i++)
		{
			ft_url = JoinString(TEXTURES_PATH, m_fileTexture[i]);
			imageData = LoadTGA(ft_url, &width, &height, &bpp);
			glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, (bpp == 24 ? GL_RGB : GL_RGBA), width, height, 0, (bpp == 24 ? GL_RGB : GL_RGBA), GL_UNSIGNED_BYTE, imageData);
			SAFE_DEL_ARRAY(ft_url);
			SAFE_DEL_ARRAY(imageData);
		}
		glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, m_wrap);
		glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, m_wrap);
		glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, m_filter);
		glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, m_filter);
	}
}
